package edu.spec.xhd.pfers;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import edu.spec.xhd.R;

public class ActivityAutoLogin extends AppCompatActivity {

    private EditText et_username;
    private EditText et_password;
    private CheckBox ckb_remember;
    private Button btn_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_login);
        initViews();
        initListeners();
    }

    private void initViews(){
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        ckb_remember = findViewById(R.id.ckb_remember);
        btn_login = findViewById(R.id.btn_login);
        SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        String username = sp.getString("username", "");
        String password = sp.getString("password", "");
        et_username.setText(username);
        et_password.setText(password);
    }

    private void initListeners(){
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Boolean isChecked = ckb_remember.isChecked();
                SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                if (isChecked){
                    String username = et_username.getText().toString();
                    String password = et_password.getText().toString();
                    editor.putString("username", username);
                    editor.putString("password", password);
                }else {
                    editor.clear();
                }
                editor.apply();
            }
        });
    }

}
